<?php
class Wechat {
    
    private $app_id = '';
    private $app_secret = '';
	
	public function __construct($appid = 'wx42c3by5587fdf4dddbc2151b67',$appsecret='d177c056955fs5as5fb67f68024d1048481a0a052'){
		$this -> app_id = $appid;
		$this -> app_secret = $appsecret;
	}

    /**
     * 获取微信授权链接
     * 
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($redirect_uri = '', $state = '1')
    {
        //$redirect_uri = urlencode($redirect_uri);
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
    }
    
    /**
     * 获取授权token
     * 
     * @param string $code 通过get_authorize_url获取到的code
     */
    public function get_access_token($code = '')
    {
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
        $token_data = $this->http($token_url);
        
        if($token_data[0] == 200)
        {
            return json_decode($token_data[1], TRUE);
        }
        
        return FALSE;
    }
    
    /**
     * 获取授权后的微信用户信息
     * 
     * @param string $access_token
     * @param string $open_id
     */
    public function get_user_info($access_token = '', $open_id = '')
    {
        if($access_token && $open_id)
        {
            $info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
            $info_data = $this->http($info_url);
            
            if($info_data[0] == 200)
            {
                return json_decode($info_data[1], TRUE);
            }
        }
        
        return FALSE;
    }
    
    public function http($url, $method='GET', $postfields = null, $headers = array(), $debug = false)
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);

            echo '=====info=====' . "\r\n";
            print_r(curl_getinfo($ci));

            echo '=====$response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return array($http_code, $response);
    }
	
	public function checkToken($openid){
		
	}
	
	public function getNormalAccessToken() {
		$path =  $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'weixin'.DIRECTORY_SEPARATOR;

	  // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
	  $data = json_decode(file_get_contents($path."access_token.json"));
	  if ($data->expire_time < time()) {
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->app_id&secret=$this->app_secret";
		$res = json_decode($this->https_request($url));
		$access_token = $res->access_token;
		if ($access_token) {
		  $data->expire_time = time() + 7000;
		  $data->access_token = $access_token;
		  $fp = fopen($path."access_token.json", "w");
		  fwrite($fp, json_encode($data));
		  fclose($fp);
		}
	  } else {
		$access_token = $data->access_token;
	  }
	  return $access_token;
	}
	
	public function getIsSub($openid){
		$token = $this -> getNormalAccessToken();
		
		$info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
            $info_data = $this->http($info_url);
            
            if($info_data[0] == 200)
            {
                return json_decode($info_data[1], TRUE);
            }
	}
	
	private function httpGet($url) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);
	 
		$res = curl_exec($curl);
		curl_close($curl);
	 
		return $res;
	  }

	//获取带参数二维码
	public function getImg($scene_id,$type = 1){
		$ticket = $this -> getTicket($scene_id,$type);
		$imgurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
		return $imageInfo = $this -> downloadImageFromWeiXin($imgurl);
	}

	//type:临时和永久1 为临时，2为永久
	public function getTicket($scene_id=122,$type=1){
		$access_token = $this -> getNormalAccessToken();
		if($type == 1){
			$qrdata = '{"expire_seconds": 604800,"action_name": "QR_SCENE","action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
		}else{
			$qrdata= '{"action_name": "QR_LIMIT_SCENE","action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
		}
		$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;

		$result = json_decode($this -> https_request($url,$qrdata));

		return $result->ticket;
	}

public function downloadImageFromWeiXin($url){
	$ch = curl_init($url);
	curl_setopt($ch,CURLOPT_HEADER,0);
	curl_setopt($ch,CURLOPT_NOBODY,0);
	curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	$package = curl_exec($ch);
	$httpinfo = curl_getinfo($ch);
	curl_close($ch);
	return array_merge(array('body'=>$package),array('header'=>$httpinfo));
}

private function https_request($url,$data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

}
